package com.ruoyi.system.outto.goods.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.UUIDGenerator;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttrTemplateMapper;
import com.ruoyi.system.V2.gameAttr.service.IGameAttributeService;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.interAttr.domain.InterAttr;
import com.ruoyi.system.interAttr.mapper.InterAttrMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.goods.IKeJinShouApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class KeJinShouApiImpl implements IKeJinShouApi {

    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    IGameAttributeService gameAttributeService;
    @Resource
    InterAttrMapper interAttrMapper;
    @Resource
    private GameAttrTemplateMapper gameAttrTemplateMapper;
    @Resource
    GoodsInfoImgMapper goodsInfoImgMapper;

    public static void main(String[] args) {
//        String games = getGames();//获取全部游戏
//        System.out.println(games);
//        getServer(211); //获取区服
        JSONArray propety = getPropety(1);// 获取商品属性
        System.out.println(propety);
    }

    static String getGames() {
        String url = "https://kejinlianmeng.com/api_up/account/config/games";
        Map params = getCove();
        String paramsStr = JSONObject.toJSONString(params);
        String response = HttpUtils.sendPost(url, paramsStr, "application/json");
        return response;
    }

    static void getServer(int gameId) {
        String url = "https://kejinlianmeng.com/api_up/account/config/servers";
        Map params = getCove();
        params.put("game_id", gameId);
        String paramsStr = JSONObject.toJSONString(params);
        String response = HttpUtils.sendPost(url, paramsStr, "application/json");
        System.out.println(response);
    }

    static JSONArray getPropety(int gameId) {
        String url = "https://kejinlianmeng.com/api_up/account/config/property";
        Map params = getCove();
        params.put("game_id", gameId);
        String paramsStr = JSONObject.toJSONString(params);
        String response = HttpUtils.sendPost(url, paramsStr, "application/json");
        Integer status = JSONObject.parseObject(response).getInteger("status");
        System.out.println(response);
        if (0 == status) {
            JSONObject jsonObject = JSONObject.parseObject(response);
            JSONArray data = JSONArray.parseArray(jsonObject.getString("data"));
            log.info("氪金兽游戏类型返回={}", JSONObject.toJSONString(data));
            return data;
        }

        return null;
    }

    static Map getCove() {
        String key = "878kjs36bfd324d8";
        String secret = "dd989607c0c5b35422a4f69d306bb0";

        JSONObject params = new JSONObject();
        params.put("key", key);
        params.put("secret", secret);
        String uuid4 = UUIDGenerator.generateUuid6();
        params.put("rand_str", uuid4);
        long time = DateUtils.getNowDate().getTime() / 1000;
        params.put("timestamp", time);
        //key + secret + rand_str + timestamp
        String oldSign = "key=" + key + ",secret=" + secret + ",rand_str=" + uuid4 + ",timestamp=" + time;
        String sign = DigestUtils.md5Hex(oldSign);
        sign = DigestUtils.sha1Hex(sign + uuid4);
        params.put("sign", sign);
        return params;
    }


    Map goodsEstablish(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {

        Map params = getCove1(salePartner);

        params.put("up_goods_id", goodsInfoAndAttrValueDto.getId().toString());
        params.put("price", goodsInfoAndAttrValueDto.getPrice().intValue());
        params.put("up_price", goodsInfoAndAttrValueDto.getPrice().intValue());
        params.put("game_account", goodsInfoAndAttrValueDto.getId().toString());
        params.put("mobile", "15173678868");
        String title = goodsInfoAndAttrValueDto.getDes();
        if (goodsInfoAndAttrValueDto.getDes().length() > 950) {
            title = goodsInfoAndAttrValueDto.getDes().substring(0, 890);
        }
        params.put("title", title);

        params = Property(goodsInfoAndAttrValueDto, params, salePartner);
        return params;
    }


    //王者荣耀参数
    private Map Property(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, SalePartner salePartner) {

        String substring = salePartner.getSaleName();
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(substring, goodsInfoAndAttrValueDto.getGameId());
        if(StringUtils.isEmpty(interAttr.getInterGameId())){
            throw new GlobalException("该游戏属性暂未匹配!!!"+goodsInfoAndAttrValueDto.getGameName());
        }
        params.put("game_id", interAttr.getInterGameId());
        String server = interAttr.getServer();
        JSONObject serjsonObject = JSONObject.parseObject(server);
        //开始匹配一级区服
        String interServeReqs = serjsonObject.getString("interServeReqs");
        String qufuid = "";
        if (Objects.equals(goodsInfoAndAttrValueDto.getGameType(), "0")) {
            qufuid = goodsInfoAndAttrValueDto.getSystemId() + "" + goodsInfoAndAttrValueDto.getCarrierId() + "";
        } else {
            qufuid = goodsInfoAndAttrValueDto.getGroupId() + "";
        }
        if(goodsInfoAndAttrValueDto.getGameName().equals("永劫无间")){
            qufuid = goodsInfoAndAttrValueDto.getServerId() + "";
        }
        if(goodsInfoAndAttrValueDto.getGameName().equals("永劫无间手游")){
            qufuid = goodsInfoAndAttrValueDto.getCarrierId() + "";
        }
        if(goodsInfoAndAttrValueDto.getGameName().equals("原神")){
            qufuid = goodsInfoAndAttrValueDto.getCarrierId() + "";
        }
        List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);

        JSONObject oneServerJson = new JSONObject();
        for (JSONObject object : oneServer) {
            String ydServeId = object.getString("YdServeId");
            if (StringUtils.isNotEmpty(ydServeId)) {
                ydServeId = ydServeId.replace(",", "").replace(" ", "");
                if (ydServeId.contains(qufuid)) {
                    oneServerJson = object;
                    break;
                }
            }
        }
        if (Objects.isNull(oneServerJson)) {
            throw new GlobalException("运营商未匹配到");
        }

        String twoServeStr = oneServerJson.getString("interServerRes");
        List<JSONObject> twoServer = JSONObject.parseArray(twoServeStr, JSONObject.class);
        JSONObject twoServerJson = new JSONObject();
        String ydID = goodsInfoAndAttrValueDto.getGroupId()+""+goodsInfoAndAttrValueDto.getServerId()+"";
        if(goodsInfoAndAttrValueDto.getGameName().equals("永劫无间手游")){
            ydID = goodsInfoAndAttrValueDto.getCarrierId() + "";
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("金铲铲之战")){
            ydID = goodsInfoAndAttrValueDto.getCarrierId() + "";
        }
        if(goodsInfoAndAttrValueDto.getGameName().equals("原神")){
            ydID = goodsInfoAndAttrValueDto.getGroupId() + "" + goodsInfoAndAttrValueDto.getServerId() + "";
        }
        if (!CollectionUtils.isEmpty(twoServer)) {
            for (JSONObject object : twoServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ","");

                    if (ydID.contains(ydServeId)) {
                        twoServerJson = object;
                        break;
                    }
                }
            }
            if (Objects.isNull(twoServerJson)) {
                throw new GlobalException("区服未匹配到");
            }
        }
        params.put("area_id", oneServerJson.getString("InterServeId"));
        if(StringUtils.isNotEmpty(twoServerJson)) {
            params.put("server_id", twoServerJson.getString("InterServeId"));
        }else {
            String interServerRes = oneServerJson.getString("interServerRes");
            if(StringUtils.isNotEmpty(interServerRes)) {
                List<JSONObject> twoServer2 = JSONObject.parseArray(interServerRes, JSONObject.class);
                if(!CollectionUtils.isEmpty(twoServer2)) {
                    params.put("server_id", twoServer2.get(0).getString("id"));
                }
            }
        }


        //========================开始匹配单选属性=====================//
        String radioAttr = interAttr.getRadioAttr();
        JSONObject jsonObject = JSONObject.parseObject(radioAttr);
        String interRadioReqs = jsonObject.getString("interRadioReqs");

        System.out.println(JSONObject.toJSONString(interRadioReqs));

//        String interRadioReqs = jsonObject.getString("interServeReqs");
        List<JSONObject> jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
        if (CollectionUtils.isEmpty(jsonObjects)) {
            throw new GlobalException("接口单选属性暂未配置");
        }
        /**
         * 1、先查询自定义中所有单选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        gameAttrTemplate.setFieldType("radio");
        List<GameAttrTemplate> gameAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();
        List<Map<String, Object>> propertys = new ArrayList<>();

        JSONArray propety = getPropety(Integer.parseInt(interAttr.getInterGameId()));
//        String des = "【编号:"+goodsInfoAndAttrValueDto.getId()+"】"+goodsInfoAndAttrValueDto.getDes();
        String des = goodsInfoAndAttrValueDto.getDes();
        if(des.length()>950){
            des = des.substring(0,950);
        }
        for(Object o : propety){
            if(JSONObject.parseObject(o.toString()).getString("title").contains("亮点")&&!JSONObject.parseObject(o.toString()).getString("title").contains("皮肤")){
                Map<String,Object> liangdian = new HashMap<>();
                liangdian.put("id",JSONObject.parseObject(o.toString()).getString("id"));
                liangdian.put("val",des);
                propertys.add(liangdian);
            }
        }

        List<JSONObject> defObjects = new ArrayList<>();
        defObjects.addAll(jsonObjects);
        for (JSONObject object : jsonObjects) {
            for (GameAttrTemplate attrTemplate : gameAttrTemplates) {
                HashMap<String, Object> mateMap = new HashMap<>();
                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        //一级属性
//                        List<JSONObject> oneAttr = jsonObjects.stream().filter(j -> Objects.equals(j.getLong("YdConfigId"), attrTemplate.getId())).collect(Collectors.toList());

                        //注意 YdConfigId 对应的是 f字段对应的 id
                        if (Objects.equals(object.getLong("YdConfigId"), attrTemplate.getId())) {
                            Integer id = object.getInteger("id");
                            defObjects.remove(object);//如果匹配上，则去掉
                            String interRadioReqs1 = object.getString("interRadioReqs");
//                            String interRadioReqs1 = object.getString("interServerRes");
                            List<JSONObject> jsonObjects2 = JSONObject.parseArray(interRadioReqs1, JSONObject.class);
                            declaredField.setAccessible(true);
                            try {
                                //获取选择的值 例如  实名中的可二次

                                Object o = declaredField.get(goodsInfoAndAttrValueDto);
                                String oneValue = String.valueOf(o);
                                List<JSONObject> twoAttr = jsonObjects2.stream().filter(j -> StringUtils.isNotEmpty(j.getString("YdConfigId"))?j.getString("YdConfigId").contains(oneValue):"111".contains(oneValue)).collect(Collectors.toList());
                                Boolean required = object.getBoolean("required");
                                String interConfigName = object.getString("InterConfigName");
                                String defaultValue = object.getString("defaultValue");
                                if (CollectionUtils.isEmpty(twoAttr) && required) {
                                    if (StringUtils.isNotEmpty(defaultValue)) {
                                        mateMap.put("id", id);
                                        mateMap.put("val", defaultValue);
                                    }
                                }
                                if (CollectionUtils.isEmpty(twoAttr) && required && StringUtils.isEmpty(defaultValue)) {
                                    throw new GlobalException("属性" + interConfigName + " 接口要求必传，但是暂未匹配到，请设置默认值");
                                }
                                if (!CollectionUtils.isEmpty(twoAttr)) {
                                    JSONObject jsonObject2 = twoAttr.get(0);
                                    String interConfigId2 = jsonObject2.getString("InterConfigId");
                                    mateMap.put("id", id);
                                    mateMap.put("val", interConfigId2);
                                    if (Objects.nonNull(mateMap.get("val"))) {
                                        propertys.add(mateMap);
                                    }
                                }
                            } catch (Exception e) {
                                throw new GlobalException("单选项" + attrTemplate.getFieldName() + "匹配错误");
                            }
                        }
                    }
                }
            }
        }
        //开始匹配默认值
        for (JSONObject object : defObjects) {
            HashMap<String, Object> mateMap = new HashMap<>();
            Integer id = object.getInteger("id");
            String interServerRes = object.getString("interServerRes");
            if(interServerRes.contains("defaultValue")) {
                JSONArray jsonArray = JSONArray.parseArray(interServerRes);
                for (Object o : jsonArray) {
                    if (StringUtils.isNotEmpty(JSONObject.parseObject(o.toString()).getString("defaultValue"))) {
                        mateMap.put("id", id);
                        mateMap.put("val", JSONObject.parseObject(o.toString()).getString("defaultValue"));
                        propertys.add(mateMap);
                    }
                }
            }
        }

        //========================单选属性匹配结束=====================//


        //========================开始匹配多选属性=====================//
        /**
         * 1、先查询自定义中所有多选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        String checkAttr = interAttr.getCheckAttr();
        JSONObject checkAttrJson = JSONObject.parseObject(checkAttr);
        String interCheckBoxReqs = checkAttrJson.getString("interCheckBoxReqs");
//        String interCheckBoxReqs = checkAttrJson.getString("interServeReqs");
        List<JSONObject> checkJsonList = JSONObject.parseArray(interCheckBoxReqs, JSONObject.class);
        if (CollectionUtils.isEmpty(jsonObjects)) {
            throw new GlobalException("接口多选属性暂未配置");
        }

        gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        List<String> types = new ArrayList<>();
        types.add("checkbox");
        types.add("boxradio");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> checkAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);

        for (JSONObject object : checkJsonList) {
            List<String> list = new ArrayList<>();
            Integer id = object.getInteger("id");
            HashMap<String, Object> mateMap = new HashMap<>();
            for (GameAttrTemplate attrTemplate : checkAttrTemplates) {
                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        declaredField.setAccessible(true);

                        String ydConfigIdLeveOne = object.getString("YdConfigId");
                        if (StringUtils.isNotEmpty(ydConfigIdLeveOne)) {

                            String[] split2 = ydConfigIdLeveOne.split(",");
                            List<String> list2 = new ArrayList<>();
                            for (String s : split2) {
                                s = s.replace(" ", "");
                                list2.add(s);
                            }
                            if (list2.contains(attrTemplate.getId() + "")) {
                                Object o = null;
                                try {
                                    o = declaredField.get(goodsInfoAndAttrValueDto);
                                } catch (IllegalAccessException e) {
                                    throw new GlobalException("多选项" + attrTemplate.getFieldName() + "匹配错误");
                                }
                                String oneValue = String.valueOf(o);
                                //一级属性
                                String ydConfigId = object.getString("YdConfigId");
                                ydConfigId = ydConfigId.replace(" ","");
                                if (StringUtils.isNotEmpty(ydConfigId)) {
                                    String[] split = ydConfigId.split(",");
                                    //一级属性已经匹配，开始匹配二级属性
                                    if (Arrays.asList(split).contains(attrTemplate.getId() + "")) {
                                        String interCheckBoxReqsStr = object.getString("interCheckBoxReqs");
//                                        String interCheckBoxReqsStr = object.getString("interServerRes");
                                        //开始匹配二级属性
                                        List<JSONObject> jsonObjects2 = JSONObject.parseArray(interCheckBoxReqsStr, JSONObject.class);
                                        /**
                                         * 咱们的f字段  多选项都是用空格 隔开，用,号切割数组，跟匹配的数据匹配、匹配上说明此账号勾选的有此属性
                                         */

                                        for (JSONObject jsonObject1 : jsonObjects2) {
                                            if (StringUtils.isNotEmpty(oneValue)) {
                                                String[] split1 = oneValue.split(",");
                                                String ydConfigId1 = jsonObject1.getString("YdConfigId");
                                                for (String s : split1) {
                                                    if (Objects.equals(s, ydConfigId1)) {
                                                        String InterConfigId2 = jsonObject1.getString("InterConfigId");
                                                        list.add(InterConfigId2);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    throw new GlobalException("属性参数错误，请匹配后重新配置");
                                }
                            }
                        }
                    }
                }
            }
            if (Objects.nonNull(id)&&!CollectionUtils.isEmpty(list)) {
                mateMap.put("id", id);
                mateMap.put("val", list);
                propertys.add(mateMap);
            }
        }
        //========================多选属性匹配完成=====================//


        //========================开始匹配输入框=====================//
        String inputAttr = interAttr.getInputAttr();
        JSONObject jsonObject1 = JSONObject.parseObject(inputAttr);
        String inputJson = jsonObject1.getString("inputJson");
        List<JSONObject> jsonObjects1 = JSONObject.parseArray(inputJson, JSONObject.class);
        gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        types = new ArrayList<>();
        types.add("number");
        types.add("input");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> inputTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        List<JSONObject> defInputObjects = new ArrayList<>();
        defInputObjects.addAll(jsonObjects1);
        for (JSONObject object : jsonObjects1) {
            for (GameAttrTemplate inputTemplate : inputTemplates) {
                HashMap<String, Object> mateMap = new HashMap<>();
                String aavName = inputTemplate.getAavName();
                if (Objects.equals(object.getString("aavName"), inputTemplate.getAavName())) {
                    defInputObjects.remove(object);
                    Integer id = object.getInteger("id");
                    for (Field declaredField : declaredFields) {
                        String name = declaredField.getName();
                        if (Objects.equals(aavName, name)) {
                            declaredField.setAccessible(true);
                            Object o = null;
                            try {
                                o = declaredField.get(goodsInfoAndAttrValueDto);
                            } catch (IllegalAccessException e) {
                                throw new GlobalException("3属性参数错误，请匹配后重新配置");
                            }
                            if(Objects.nonNull(o)) {
                                String oneValue = String.valueOf(o);
//                            Boolean required = object.getBoolean("required");
//                            if (required && StringUtils.isEmpty(oneValue)) {
//                                throw new GlobalException(aavNameInter + "必传，但是该商品没有该值");
//                            }
                                mateMap.put("id", id);
                                mateMap.put("val", oneValue);
                                propertys.add(mateMap);
                            }
                        }
                    }
                }
            }
        }

        //开始匹配默认值
        for (JSONObject object : defInputObjects) {
            HashMap<String, Object> mateMap = new HashMap<>();
            Integer id = object.getInteger("id");
            String defaultValue = object.getString("defaultValue");
            if (StringUtils.isNotEmpty(defaultValue)) {
                mateMap.put("id", id);
                mateMap.put("val", defaultValue);
                if (Objects.nonNull(mateMap.get("val"))) {
                    propertys.add(mateMap);
                }
            }
        }


        //========================匹配图片属性，因为氪金兽图片属性是自定义字段，所以要单独开发  这里只做一个王者荣耀的=====================//
        if (Objects.equals("王者荣耀", goodsInfoAndAttrValueDto.getGameName())) {
            propertys.addAll(addYXJTMap("48", "1452", "1454", goodsInfoAndAttrValueDto.getId(), goodsInfoAndAttrValueDto.getTitleImg()));
        } else if (Objects.equals("和平精英", goodsInfoAndAttrValueDto.getGameName())) {
            //自己查一下和平的属性  填上
            propertys.addAll(addYXJTMap("277", "1457", "1457", goodsInfoAndAttrValueDto.getId(), goodsInfoAndAttrValueDto.getTitleImg()));
        } else if (Objects.equals("英雄联盟", goodsInfoAndAttrValueDto.getGameName())) {
            propertys.addAll(addYXJTMap("47", "1497", "1496", goodsInfoAndAttrValueDto.getId(), goodsInfoAndAttrValueDto.getTitleImg()));
        } else if (Objects.equals("火影忍者", goodsInfoAndAttrValueDto.getGameName())) {
            propertys.addAll(addYXJTMap("217", "1940", null, goodsInfoAndAttrValueDto.getId(), goodsInfoAndAttrValueDto.getTitleImg()));
        } else if (Objects.equals("原神", goodsInfoAndAttrValueDto.getGameName())) {
            propertys.addAll(addYXJTMap("139", "1451", "1453", goodsInfoAndAttrValueDto.getId(), goodsInfoAndAttrValueDto.getTitleImg()));
        } else if (Objects.equals("穿越火线", goodsInfoAndAttrValueDto.getGameName())) {
            propertys.addAll(addYXJTMap("201", "203", null, goodsInfoAndAttrValueDto.getId(), goodsInfoAndAttrValueDto.getTitleImg()));
        } else if (Objects.equals("枪战王者", goodsInfoAndAttrValueDto.getGameName())) {
            propertys.addAll(addYXJTMap("245", "488", "1934", goodsInfoAndAttrValueDto.getId(), goodsInfoAndAttrValueDto.getTitleImg()));
        } else if (Objects.equals("永劫无间", goodsInfoAndAttrValueDto.getGameName())) {
            propertys.addAll(addYXJTMap("95", "1498", "1499", goodsInfoAndAttrValueDto.getId(), goodsInfoAndAttrValueDto.getTitleImg()));
        } else if (Objects.equals("永劫无间手游", goodsInfoAndAttrValueDto.getGameName())) {
            propertys.addAll(addYXJTMap("4151", null, null, goodsInfoAndAttrValueDto.getId(), goodsInfoAndAttrValueDto.getTitleImg()));
        } else if (Objects.equals("金铲铲之战", goodsInfoAndAttrValueDto.getGameName())) {
            propertys.addAll(addYXJTMap("255", "486", "832", goodsInfoAndAttrValueDto.getId(), goodsInfoAndAttrValueDto.getTitleImg()));
        } else if (Objects.equals("使命召唤", goodsInfoAndAttrValueDto.getGameName())) {
            propertys.addAll(addYXJTMap("385", "539", "1361", goodsInfoAndAttrValueDto.getId(), goodsInfoAndAttrValueDto.getTitleImg()));
        } else if (Objects.equals("英雄联盟(手游)", goodsInfoAndAttrValueDto.getGameName())) {
            Map<String,Object> imgs = new HashMap<>();
            GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
            goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
            goodsInfoImg.setType(Constants.STR_1);
            List<GoodsInfoImg> goodsInfoImgList = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
            imgs.put("id","252");
            List<String> collect = new ArrayList<>();
            if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getTitleImg())){
                collect.add(goodsInfoAndAttrValueDto.getTitleImg());
            }
            if (goodsInfoImgList.size() > 50) {
                goodsInfoImgList = goodsInfoImgList.subList(0, 49);
            }
            for (GoodsInfoImg goodsInfoImg1 : goodsInfoImgList){
                collect.add(goodsInfoImg1.getImgUrl());
            }
            imgs.put("val", collect);
            propertys.add(imgs);
        } else if (Objects.equals("无畏契约", goodsInfoAndAttrValueDto.getGameName())) {
            propertys.addAll(addYXJTMap("1091", "1380", null, goodsInfoAndAttrValueDto.getId(), goodsInfoAndAttrValueDto.getTitleImg()));
        } else if (Objects.equals("暗区突围", goodsInfoAndAttrValueDto.getGameName())) {
            propertys.addAll(addYXJTMap("399", "5247", null, goodsInfoAndAttrValueDto.getId(), goodsInfoAndAttrValueDto.getTitleImg()));
        } else if (Objects.equals("三角洲行动", goodsInfoAndAttrValueDto.getGameName())) {
            Map<String,Object> imgs = new HashMap<>();
            GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
            goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
            goodsInfoImg.setType(Constants.STR_1);
            List<GoodsInfoImg> goodsInfoImgList = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
            imgs.put("id","4668");
            List<String> collect = new ArrayList<>();
            if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getTitleImg())){
                collect.add(goodsInfoAndAttrValueDto.getTitleImg());
            }
            if (goodsInfoImgList.size() > 50) {
                goodsInfoImgList = goodsInfoImgList.subList(0, 49);
            }
            for (GoodsInfoImg goodsInfoImg1 : goodsInfoImgList){
                collect.add(goodsInfoImg1.getImgUrl());
            }
            imgs.put("val", collect);
            propertys.add(imgs);
        }else if (Objects.equals("使命召唤手游", goodsInfoAndAttrValueDto.getGameName())) {
            propertys.addAll(addYXJTMap("539", "1361", null, goodsInfoAndAttrValueDto.getId(), goodsInfoAndAttrValueDto.getTitleImg()));
        }
//        propertys.addAll(addYXJTMap("48","1452","1454",goodsInfoAndAttrValueDto.getId(),goodsInfoAndAttrValueDto.getTitleImg()));
//        String propertyJson = JSONObject.toJSONString(propertys);
        params.put("property", JSONObject.toJSONString(propertys));
        return params;
    }


    Map getCove1(SalePartner salePartner) {
        String key = salePartner.getSaleKey();
        String secret = salePartner.getOther();

        JSONObject params = new JSONObject();
        params.put("key", key);
        params.put("secret", secret);
        String uuid4 = UUIDGenerator.generateUuid6();
        params.put("rand_str", uuid4);
        long time = DateUtils.getNowDate().getTime() / 1000;
        params.put("timestamp", time);
        //key + secret + rand_str + timestamp
        String oldSign = "key=" + key + ",secret=" + secret + ",rand_str=" + uuid4 + ",timestamp=" + time;
        String sign = DigestUtils.md5Hex(oldSign);
        sign = DigestUtils.sha1Hex(sign + uuid4);
        params.put("sign", sign);
        return params;
    }


    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner
            salePartner) {

        String paramsStr = JSONObject.toJSONString(goodsEstablish(goodsInfoAndAttrValueDto, salePartner));
        log.info("氪金兽游新增请求参数={}", paramsStr);
        String url = "https://kejinlianmeng.com/api_up/account/goods/establish";
        String response = HttpUtils.sendPost(url, paramsStr, "application/json");
//        String response = "{    \"status\": 5,    \"message\": \"app key 不能为空!, rand str 必须填写, timestamp 必须填写, sign 必须填写\"}";
        JSONObject resultJson = JSONObject.parseObject(response);
        Map<String, Object> result = new HashMap<>();

        if (!"0".equals(resultJson.getString("status"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);

            JSONObject jsonObject = JSONObject.parseObject(response);
            JSONObject data = jsonObject.getJSONObject("data");
            Long id = data.getLong("id");
//            result.put("outId", );
            ArtRec artRecreq = new ArtRec();
            artRecreq.setConfig(salePartner.getId());
            artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
            List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(artRecs)) {
                artRecs.get(0).setOutid(id.toString());
                artRecMapper.updateArtRec(artRecs.get(0));
            } else {
                artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
                artRecreq.setCreateId(goodsInfoAndAttrValueDto.getCreateId());
                artRecreq.setType(LCConstant.interAdd);
                artRecreq.setConfig(salePartner.getId());
                artRecreq.setSaleCode(salePartner.getSaleName());
                artRecreq.setOutid(id.toString());
                artRecMapper.insertArtRec(artRecreq);
            }
            goodsUpper(String.valueOf(id), salePartner);
        }
        result.put("req", paramsStr);
        result.put("res", response);
        result.put("msg", resultJson.getString("message"));
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,
                               SalePartner salePartner) {
        return addGame(goodsInfoAndAttrValueDto, salePartner);
    }

//    public void upGame(,
//                               SalePartner salePartner) {
//        return addGame(goodsInfoAndAttrValueDto, salePartner);
//    }


    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner
            salePartner) {
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        Map<String, Object> result = new HashMap<>();
        if (!CollectionUtils.isEmpty(artRecs)) {
            //先下架
            ArtRec artRec = artRecs.get(0);
            if (StringUtils.isNotEmpty(artRec.getOutid())) {
                result = goodsUnder(artRec.getOutid(), salePartner, goodsInfoAndAttrValueDto);
                //删除接口未开放
//                String response = goodsDelete(artRec.getOutid());
            } else {
                throw new GlobalException("商品id为 " + goodsInfoAndAttrValueDto.getId() + " 在供应商id为" + salePartner.getId() +
                        "下的关联id为空,请查看");
            }
        } else {
            throw new GlobalException("商品id为 " + goodsInfoAndAttrValueDto.getId() + " 在供应商id为" + salePartner.getId() +
                    "下的关联id异常,请查看");
        }
        return AjaxResult.success(result);
    }

    /**
     * 下架接口
     *
     * @param kjsId
     * @param salePartner
     * @return
     */
    Map<String, Object> goodsUnder(String kjsId, SalePartner salePartner,
                                   GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto) {
        Map<String, Object> sign = getCove1(salePartner);
        sign.put("id", kjsId);
        String paramsStr = JSONObject.toJSONString(sign);
        String upperurl = "https://kejinlianmeng.com/api_up/account/goods/under";
        //先下架
        String response = HttpUtils.sendPost(upperurl, paramsStr, "application/json");
        log.info("氪金兽游戏下架返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        Map<String, Object> result = new HashMap<>();
        if (!"0".equals(resultJson.getString("status"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
            artRecMapper.deleteArtRecCode(goodsInfoAndAttrValueDto.getId(), salePartner.getId());
        }
        result.put("req", paramsStr);
        result.put("res", response);
        result.put("msg", resultJson.getString("message"));
        return result;
    }

    /**
     * 上架接口
     *
     * @param kjsId
     * @param salePartner
     * @return
     */
    String goodsUpper(String kjsId, SalePartner salePartner) {
        Map<String, Object> sign = getCove1(salePartner);
        sign.put("id", kjsId);
        String paramsStr = JSONObject.toJSONString(sign);
        String upperurl = "https://kejinlianmeng.com/api_up/account/goods/upper";
        String response = HttpUtils.sendPost(upperurl, paramsStr, "application/json");
//        log.info("氪金兽游戏下架返回参数={}", response);
//        JSONObject resultJson = JSONObject.parseObject(response);
//        Map<String, Object> result = new HashMap<>();
//        if (!"0".equals(resultJson.getString("status"))) {
//            result.put("code", 500);
//        } else {
//            result.put("code", 200);
//        }
//        result.put("req", paramsStr);
//        result.put("res", response);
//        result.put("msg", resultJson.getString("message"));
        return response;
    }

    String goodsDelete(String kjsId, SalePartner salePartner) {
        Map<String, Object> sign = getCove1(salePartner);
        sign.put("id", kjsId);
        String paramsStr = JSONObject.toJSONString(sign);
        String upperurl = "https://kejinlianmeng.com/api_up/account/goods/delete";
        //删除
        String response = HttpUtils.sendPost(upperurl, paramsStr, "application/json");
        return response;
    }

    // 将英文括号替换成中文括号
    private String replaceStr(final String str) {
        String newNode = null;
        String allConvertNode = null;
        // 替换英文括号的时候因为正则表达式问题，英文前括号和后括号的前边都要加上\\
        if (str.contains("(") && str.contains(")")) {
            newNode = str.replaceAll("\\(", "（");
            allConvertNode = newNode.replaceAll("\\)", "）");
        } else if (str.contains("(") && !str.contains(")")) {
            allConvertNode = str.replaceAll("\\(", "（");
        } else if (!str.contains("(") && str.contains(")")) {
            allConvertNode = str.replaceAll("\\)", "）");
        } else {
            allConvertNode = str;
        }
        return allConvertNode;
    }


    /**
     * 游戏截图Map 添加
     * gameImgeId 游戏截图
     * titelImgId1 首图
     * titelImgId2 首图
     */
    private List<Map<String, Object>> addYXJTMap(String gameImgeId, String titelImgId1, String titelImgId2, Long goodsId, String titleImg) {
        List<Map<String, Object>> propertys = new ArrayList<>();
        if (StringUtils.isNotEmpty(gameImgeId)) {
            Map<String, Object> imgs2 = new HashMap<>();
            imgs2.put("id", gameImgeId);
            GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
            goodsInfoImg.setGoodsId(goodsId);
            goodsInfoImg.setType(Constants.STR_1);
            List<GoodsInfoImg> goodsInfoImgList = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
            if (CollectionUtils.isEmpty(goodsInfoImgList)) {
                ArrayList<String> initImg = new ArrayList<>();
                initImg.add("https://game.ikbh.top/logo/no_img.jpg");
                imgs2.put("val", initImg);
            } else if (goodsInfoImgList.size() > 50) {
                List<String> collect = goodsInfoImgList.subList(0, 49).stream().map(img -> img.getImgUrl()).collect(Collectors.toList());
                log.info(collect.toString());
                imgs2.put("val", collect);
            } else {
                List<String> collect = goodsInfoImgList.stream().map(img -> img.getImgUrl()).collect(Collectors.toList());
                log.info(collect.toString());
                imgs2.put("val", collect);
            }
            propertys.add(imgs2);
        }
        if (StringUtils.isNotEmpty(titelImgId1)) {
            Map<String, Object> imgsOne = new HashMap<>();
            imgsOne.put("id", titelImgId1);
            imgsOne.put("val", titleImg);
            propertys.add(imgsOne);
        }

        if (StringUtils.isNotEmpty(titelImgId2)) {
            Map<String, Object> imgsTwo = new HashMap<>();
            imgsTwo.put("id", titelImgId2);
            imgsTwo.put("val", titleImg);
            propertys.add(imgsTwo);
        }

        return propertys;
    }

    /**
     * 亮点Map 添加
     */
    private void addLDMap(JSONObject jsonObject, GoodsInfoAndAttrValueDto
            goodsInfoAndAttrValueDto, List<Map<String,
            Object>> propertys) {
        String outId = jsonObject.getString("id");
        Map<String, Object> desmap = new HashMap<>();
        desmap.put("id", outId);
        String des = goodsInfoAndAttrValueDto.getId() + goodsInfoAndAttrValueDto.getDes();
        if (StringUtils.isEmpty(des)) {
            desmap.put("val", "---");
        } else {
            desmap.put("val", des.length() < 200 ? des : des.substring(0, 199));
        }
        propertys.add(desmap);
    }

    /**
     * 必填 redio单选 添加 公共map
     *
     * @param str        判断是什么信息
     * @param jsonObject 获取到的jsonObject
     * @param goodsId    商品id
     * @param filedReq   根据是什么信息 传 对应的商品字段
     * @param propertys  载体
     */
    private void addxxMapRedioTrue(String str, JSONObject jsonObject, Long goodsId, String filedReq, List<Map<String,
            Object>> propertys) {
        String val = jsonObject.getString("val");
        String outId = jsonObject.getString("id");
        JSONArray parse = JSONArray.parseArray(val);
        Map<String, Object> xxMap = new HashMap<>();
        String xxId = "0";
        if (StringUtils.isNotEmpty(filedReq)) {
            GameAttribute gameAttribute =
                    gameAttributeService.selectGameAttributeById(Long.valueOf(filedReq));
            if (gameAttribute != null) {
                for (Object o : parse) {
                    String skinObj = JSON.toJSONString(o);
                    JSONObject skinObjJson = JSONObject.parseObject(skinObj);
                    String title = skinObjJson.getString("title");
                    if (StringUtils.equals(title, "已删人脸实名随时可以认证")) {
                        title = "已删人脸实名可随时认证";
                    }
                    String id = skinObjJson.getString("id");
                    if (StringUtils.equals(gameAttribute.getFieldName(), title)) {
                        xxId = id;
                        break;
                    }
                }
                if (StringUtils.equals(xxId, "0")) {
                    throw new GlobalException("id为" + goodsId + "<" + str + ">" + "未匹配成功");
                }
                xxMap.put("id", outId);
                xxMap.put("val", xxId);
                propertys.add(xxMap);
            } else {
                throw new GlobalException("id为" + goodsId + "无<" + str + ">");
            }
        } else {
            throw new GlobalException("id为" + goodsId + "无<" + str + ">");
        }
    }

    /**
     * 非必填 redio单选 添加 公共map
     *
     * @param jsonObject 获取到的jsonObject
     * @param value      属性id
     * @param propertys  载体
     */
    private void addxxMapRedio(JSONObject jsonObject, String value, List<Map<String, Object>> propertys) {
        if (StringUtils.isNotEmpty(value)) {
            GameAttribute gameAttributeds =
                    gameAttributeService.selectGameAttributeById(Long.valueOf(value));
            if (gameAttributeds != null) {
                String val = jsonObject.getString("val");
                String outId = jsonObject.getString("id");
                JSONArray parse = JSONArray.parseArray(val);
                Map<String, Object> xxMap = new HashMap<>();
                String xxId = "0";
                for (Object o : parse) {
                    String skinObj = JSON.toJSONString(o);
                    JSONObject skinObjJson = JSONObject.parseObject(skinObj);
                    String title = skinObjJson.getString("title");
                    String id = skinObjJson.getString("id");
                    if (StringUtils.equals(gameAttributeds.getFieldName(), title)) {
                        xxId = id;
                        break;
                    }
                }
                if (!xxId.equals("0")) {
                    xxMap.put("id", outId);
                    xxMap.put("val", xxId);
                    propertys.add(xxMap);
                }
            }
        }
    }

}